using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Ioc;
using System.Linq;
using JmShared;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Threading;
using System.IO;
using System.Xml;
using System.Windows.Input;
using System.Diagnostics;
using System.Collections.Specialized;
using JiveMessenger.User;
using System.Windows;
using System.ComponentModel;
using JiveMessenger.Utilities;
//using System.Reflection;
using Windows.UI.Core;
using System.Threading.Tasks;
using GalaSoft.MvvmLight.Threading;
using GalaSoft.MvvmLight.Views;
using JiveMessenger.Models;
using Windows.UI.Xaml;
using Windows.Graphics.Display;


namespace JiveMessenger.ViewModels
{
    public class ViewModelMainPage : ViewModelBaseEx, IViewModelMainPage
    {
        private INavigationService _navigationService;
        private object LockObject = new object();

        public RelayCommand EditFontCommand { get; set; }
        public RelayCommand GetEmoticonsCommand { get; set; }
        public RelayCommand<bool> DisconnectCommand { get; set; }
        public RelayCommand LoginCommand { get; set; }
        public RelayCommand OpenOptionsCommand { get; set; }
        public RelayCommand<ViewModelTab> CloseTabCommand { get; set; }
        public RelayCommand OpenNotificationsCommand { get; set; }
        public RelayCommand<ViewModelTab> CloseAllTabsCommand { get; set; }
        public RelayCommand<ViewModelTab> PinTabCommand { get; set; }
        public RelayCommand<object> ShowLoginControlCommand { get; set; }
        public RelayCommand ShowTabListCommand { get; set; }
        public RelayCommand<ViewModelTab> SelectTabCommand { get; set; }
        public RelayCommand<IChatGroup> CreateDummyConversationCommand { get; set; }
        public RelayCommand OpenEmoticonsCommand { get; set; }
        public RelayCommand<ViewModelChat> OpenDownloadMessagesCommand { get; set; }
        public RelayCommand CloseTabsListCommand { get; set; }

        private IClient _currentClient { get; set; }
        private string _jiveIcon;
        public string JiveIcon
        {
            get { return _jiveIcon; }
            set
            {
                if (_jiveIcon != value)
                {
                    Set(() => JiveIcon, ref _jiveIcon, value);
                }
            }
        }

        public string EmptyClientListText
        {
            get
            {
                if (_currentClient.IsLoggedIn)
                    return "The contact list is empty. You can add contacts from the application bar.";
                else
                    return "Log in to see your contacts.";
            }
        }

        private ObservableCollection<ViewModelTab> _chatViewModels;
        public ObservableCollection<ViewModelTab> ChatViewModels
        {
            get { return _chatViewModels; }
            set
            {
                if (_chatViewModels != value)
                {
                    if (_chatViewModels != null)
                        _chatViewModels.CollectionChanged -= ChatViewModels_CollectionChanged;
                    Set(() => ChatViewModels, ref _chatViewModels, value);
                    if (_chatViewModels != null)
                        _chatViewModels.CollectionChanged += ChatViewModels_CollectionChanged;
                }
            }
        }



        private ViewModelTab _currentChatViewModel;
        public ViewModelTab CurrentActiveViewModel
        {
            get { return _currentChatViewModel; }
            set
            {
                if (_currentChatViewModel != value)
                {
                    if (_currentChatViewModel != null)
                        _currentChatViewModel.IsCurrentActiveTab = false;

                    Set(() => CurrentActiveViewModel, ref _currentChatViewModel, value);

                    if (_currentChatViewModel != null)
                        _currentChatViewModel.IsCurrentActiveTab = true;

                    if (value == null)
                        IsChatControlVisible = false;
                    else
                    {
                        IsChatControlVisible = true;
                        if (value is ViewModelPrivateMessage)
                        {
                            ((ViewModelPrivateMessage)value).PmTarget.UnreadMessageCount = 0;
                        }
                        value.IsBlinking = false;
                    }
                    OpenEmoticonsCommand.RaiseCanExecuteChanged();
                    OpenDownloadMessagesCommand.RaiseCanExecuteChanged();
                }
            }
        }



        private bool _isMainMenuVisible;
        public bool IsMainMenuVisible
        {
            get { return _isMainMenuVisible; }
            set
            {
                if (_isMainMenuVisible != value)
                {
                    Set(() => IsMainMenuVisible, ref _isMainMenuVisible, value);
                }
            }
        }

        private bool _isTabListOpen;
        public bool IsTabListOpen
        {
            get { return _isTabListOpen; }
            set
            {
                if (_isTabListOpen != value)
                {
                    Set(() => IsTabListOpen, ref _isTabListOpen, value);
                    if (value == true)
                        IsLoginControlVisible = false;
                }
            }
        }


        private string _windowTitle;
        public string WindowTitle
        {
            get { return _windowTitle; }
            set
            {
                if (_windowTitle != value)
                {
                    Set(() => WindowTitle, ref _windowTitle, value);
                }
            }
        }

        private bool _isLoginControlVisible;
        public bool IsLoginControlVisible
        {
            get { return _isLoginControlVisible; }
            set
            {
                if (_isLoginControlVisible != value)
                {
                    Set(() => IsLoginControlVisible, ref _isLoginControlVisible, value);
                    if (value == true)
                        IsTabListOpen = false;
                }
            }
        }

        private bool _isChatControlVisible;
        public bool IsChatControlVisible
        {
            get { return _isChatControlVisible; }
            set
            {
                if (_isChatControlVisible != value)
                {
                    Set(() => IsChatControlVisible, ref _isChatControlVisible, value);
                }
            }
        }



        private string _connectButtonDisplayText;
        public string ConnectButtonDisplayText
        {
            get { return _connectButtonDisplayText; }
            set
            {
                if (_connectButtonDisplayText != value)
                {
                    Set(() => ConnectButtonDisplayText, ref _connectButtonDisplayText, value);
                }
            }
        }

        private int _selectedPivotItemIndex;
        public int SelectedPivotItemIndex
        {
            get { return _selectedPivotItemIndex; }
            set
            {
                if (_selectedPivotItemIndex != value)
                {
                    Set(() => SelectedPivotItemIndex, ref _selectedPivotItemIndex, value);
                }
            }
        }

        private int _emoticonControlPivotIndex;
        public int EmoticonControlPivotIndex
        {
            get { return _emoticonControlPivotIndex; }
            set
            {
                if (_emoticonControlPivotIndex != value)
                {
                    Set(() => EmoticonControlPivotIndex, ref _emoticonControlPivotIndex, value);
                    AppSettings.Instance.LastOpenedEmoticonPageIndex = value;
                }
            }
        }

        private Uri _emoticonButtonIconUri;
        public Uri EmoticonButtonIconUri
        {
            get { return _emoticonButtonIconUri; }
            set
            {
                if (_emoticonButtonIconUri != value)
                {
                    Set(() => EmoticonButtonIconUri, ref _emoticonButtonIconUri, value);
                }
            }
        }



        private string _emoticonButtonDisplayText;
        public string EmoticonButtonDisplayText
        {
            get { return _emoticonButtonDisplayText; }
            set
            {
                if (_emoticonButtonDisplayText != value)
                {
                    Set(() => EmoticonButtonDisplayText, ref _emoticonButtonDisplayText, value);
                }
            }
        }

        private Uri _connectButtonIconUri;
        public Uri ConnectButtonIconUri
        {
            get { return _connectButtonIconUri; }
            set
            {
                if (_connectButtonIconUri != value)
                {
                    Set(() => ConnectButtonIconUri, ref _connectButtonIconUri, value);
                }
            }
        }

        private Uri _tabButtonImageUri;
        public Uri TabButtonImageUri
        {
            get { return _tabButtonImageUri; }
            set
            {
                if (_tabButtonImageUri != value)
                {
                    Set(() => TabButtonImageUri, ref _tabButtonImageUri, value);
                }
            }
        }

        private Windows.UI.ViewManagement.ApplicationViewOrientation _deviceOrientation;
        public Windows.UI.ViewManagement.ApplicationViewOrientation DeviceOrientation
        {
            get { return _deviceOrientation; }
            set
            {
                if (_deviceOrientation != value)
                {
                    Set(() => DeviceOrientation, ref _deviceOrientation, value);
                }
            }
        }

        private bool _showFauxKeyboardGrid;
        public bool ShowFauxKeyboardGrid
        {
            get { return _showFauxKeyboardGrid; }
            set
            {
                if (_showFauxKeyboardGrid != value)
                {
                    Set(() => ShowFauxKeyboardGrid, ref _showFauxKeyboardGrid, value);
                    if (this.CurrentActiveViewModel != null && this.CurrentActiveViewModel is ViewModelChat)
                        ((ViewModelChat)this.CurrentActiveViewModel).ShowFauxKeyboardGrid = value;
                }
            }
        }




        private bool _showEmoticonPopup;
        public bool ShowEmoticonPopup
        {
            get { return _showEmoticonPopup; }
            set
            {
                if (_showEmoticonPopup != value)
                {
                    ViewModelChat chatVm = this.CurrentActiveViewModel as ViewModelChat;
                    if (!chatVm.IsInputTextFocused && value == false)
                        Messenger.Default.Send(new NotificationMessage(this, "RemoveFakeKeyboardAnimation"));
                    else
                        Messenger.Default.Send(new NotificationMessage(this, "ShowFakeKeyboardAnimation"));

                    Set(() => ShowEmoticonPopup, ref _showEmoticonPopup, value);

                    if (value == true)
                    {
                        chatVm.IsInputTextFocused = false;
                        Messenger.Default.Send(new NotificationMessage(this, "SetKeyboardAppButtonIcon"));
                        IsTabListOpen = false;
                        IsLoginControlVisible = false;
                    }
                    else
                        Messenger.Default.Send(new NotificationMessage(this, "SetEmoticonAppButtonIcon"));
                    if (!chatVm.IsInputTextFocused)
                        ShowFauxKeyboardGrid = this.ShowEmoticonPopup;
                }
            }
        }


        private double _emoticonControlHeight;
        public double EmoticonControlHeight
        {
            get { return _emoticonControlHeight; }
            set
            {
                if (_emoticonControlHeight != value)
                {
                    Set(() => EmoticonControlHeight, ref _emoticonControlHeight, value);
                }
            }
        }
        private double _fauxKeyboardHeight;
        public double FauxKeyboardHeight
        {
            get { return _fauxKeyboardHeight; }
            set
            {
                if (_fauxKeyboardHeight != value)
                {
                    Set(() => FauxKeyboardHeight, ref _fauxKeyboardHeight, value);
                }
            }
        }


        private double _emoticonControlWidth;
        public double EmoticonControlWidth
        {
            get { return _emoticonControlWidth; }
            set
            {
                if (_emoticonControlWidth != value)
                {
                    Set(() => EmoticonControlWidth, ref _emoticonControlWidth, value);
                }
            }
        }

        public ViewModelMainPage() : base() { }
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public ViewModelMainPage(IClient currentClient, INavigationService service)
        {
            _navigationService = service;


            ConnectButtonIconUri = new Uri("ms-appx:///Assets/AppBar/appbar.door.enter.png");
            EmoticonButtonIconUri = new Uri("ms-appx:///Assets/AppBar/appbar.smiley.happy.png");
            ConnectButtonDisplayText = "Log in";
            EmoticonButtonDisplayText = "Emoticons";
            EmoticonControlHeight = 340;
            EmoticonControlWidth = 400;
            FauxKeyboardHeight = 340;
            RefreshIcons();
            if (IsInDesignMode)
            {
            }
            else
            {
                //#if DEBUG
                //                IsDebug = true;
                //#endif
                Window.Current.Activated += Current_Activated;
                SelectedPivotItemIndex = 1;
                _currentClient = currentClient;
                IsMainMenuVisible = false;
                WindowTitle = "Jive Messenger";
                ChatViewModels = new ObservableCollection<ViewModelTab>();
                GetEmoticonsCommand = new RelayCommand(GetEmoticonsCommandAction, () => _currentClient.IsLoggedIn);
                DisconnectCommand = new RelayCommand<bool>(DisconnectCommandAction, (x) => _currentClient.IsLoggedIn);
                OpenOptionsCommand = new RelayCommand(OpenOptionsCommandAction);
                EditFontCommand = new RelayCommand(EditFontCommandAction, () => _currentClient.IsLoggedIn);
                OpenNotificationsCommand = new RelayCommand(OpenNotificationsWindowCommandAction);
                CloseTabCommand = new RelayCommand<ViewModelTab>(CloseTabCommandAction);//, (tab) => _currentClient.IsLoggedIn);
                CloseAllTabsCommand = new RelayCommand<ViewModelTab>(CloseAllTabsCommandAction);//, (tab) => _currentClient.IsLoggedIn);
                PinTabCommand = new RelayCommand<ViewModelTab>(PinTabCommandAction, (tab) => CurrentActiveViewModel != null);
                LoginCommand = new RelayCommand(LoginCommandAction);
                // EmoticonControlPivotIndex = AppSettings.Instance.LastOpenedEmoticonPageIndex;
                ShowLoginControlCommand = new RelayCommand<object>(ShowLoginControlCommandAction);
                ShowTabListCommand = new RelayCommand(ShowTabListCommandAction, () => ChatViewModels.Count > 0);
                SelectTabCommand = new RelayCommand<ViewModelTab>(SelectTabCommandAction);
                CreateDummyConversationCommand = new RelayCommand<IChatGroup>(CreateDummyConversationCommandAction);
                OpenEmoticonsCommand = new RelayCommand(OpenEmoticonsCommandAction, () => CurrentActiveViewModel != null && CurrentActiveViewModel is ViewModelChat && _currentClient.IsLoggedIn);
                OpenDownloadMessagesCommand = new RelayCommand<ViewModelChat>(OpenDownloadMessagesCommandAction, vm => vm != null && vm is ViewModelChat);
                CloseTabsListCommand = new RelayCommand(CloseTabsListCommandAction);
                //DefaultEmoticons = CreateDefaultEmoticonList();

                Messenger.Default.Register<NotificationMessage<ViewModelChat>>(this, msg =>
                    {
                        switch (msg.Notification)
                        {
                            case "OpenGroup":
                                OpenGroup(msg.Content as ViewModelChat);
                                break;
                        }
                    });
                Messenger.Default.Register<NotificationMessage<string>>(this, msg =>
                    {
                        switch (msg.Notification)
                        {
                            case "CloseTab":
                                ViewModelTab tab = ChatViewModels.FirstOrDefault(x => x.ID == msg.Content);
                                if (tab != null)
                                {
                                    CloseTabCommand.Execute(tab);
                                }
                                break;
                        }
                    });

                Messenger.Default.Register<NotificationMessage>(this, msg =>
                    {
                        switch (msg.Notification)
                        {
                            case "SetKeyboardAppButtonIcon":
                                EmoticonButtonDisplayText = "Keyboard";
                                EmoticonButtonIconUri = new Uri("ms-appx:///Assets/AppBar/appbar.input.keyboard.png");
                                break;
                            case "SetEmoticonAppButtonIcon":
                                EmoticonButtonDisplayText = "Emoticons";
                                EmoticonButtonIconUri = new Uri("ms-appx:///Assets/AppBar/appbar.smiley.happy.png");
                                break;
                            case "HideEmoticonPopup":
                                ShowFauxKeyboardGrid = false;
                                ShowEmoticonPopup = false;
                                break;

                        }
                    });

                Messenger.Default.Register<NotificationMessage<bool>>(this, msg =>
                    {
                        switch (msg.Notification)
                        {
                            case "IsInputTextFocused":
                                ShowFauxKeyboardGrid = true;
                                ShowEmoticonPopup = false;

                                if (!ShowEmoticonPopup && msg.Content == false)
                                    Messenger.Default.Send(new NotificationMessage(this, "RemoveFakeKeyboardAnimation"));
                                else
                                    Messenger.Default.Send(new NotificationMessage(this, "ShowFakeKeyboardAnimation"));
                                break;
                        }
                    });
                CreateTabButtonImage();
            }
        }

        void Current_Activated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
        {
            RefreshIcons();
        }
        private void CloseTabsListCommandAction()
        {
            this.IsTabListOpen = false;
        }

        private void OpenDownloadMessagesCommandAction(ViewModelChat vm)
        {
            MessageDownloadParameter parameter = null;
            if (vm is ViewModelGroupChat)
                parameter = new MessageDownloadParameter(this.CurrentActiveViewModel.ID, 30, 250, this.CurrentActiveViewModel.ViewModelName, ChatType.GroupChat);
            else if (vm is ViewModelPrivateMessage)
                parameter = new MessageDownloadParameter(this.CurrentActiveViewModel.ID, 196, 250, this.CurrentActiveViewModel.ViewModelName, ChatType.PrivateMessage);


            if (parameter != null)
                _navigationService.NavigateTo("MessageDownloadPage", parameter);
        }

        private void OpenEmoticonsCommandAction()
        {
            if (ShowEmoticonPopup)
            {
                ((ViewModelChat)this.CurrentActiveViewModel).IsInputTextFocused = true;
                ShowEmoticonPopup = false;

                return;
            }

            ShowEmoticonPopup = true;
        }
        private void CreateDummyConversationCommandAction(IChatGroup group)
        {
            if (!(group is JiveChatGroupModel))
                return;
            ViewModelChat chat = this.ChatViewModels.FirstOrDefault(x => x.ID == group.ID) as ViewModelChat;
            if (chat == null)
            {
                //Messenger.Default.Send(new NotificationMessageAction<IContact>(this, _currentClient.CurrentUserInfo.UserID, "GetContactFromUserID", contact =>
                //    {
                chat = new ViewModelGroupChat(_currentClient, group);
                OpenGroup(chat);
                //}));
            }
            Random r = new Random();
            string[] text = {"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Idemne, quod iucunde? Omnia contraria, quos etiam insanos esse vultis. Hoc mihi cum tuo fratre convenit. Quae diligentissime contra Aristonem dicuntur a Chryippo. Honesta oratio, Socratica, Platonis etiam. Et nemo nimium beatus est;",

                            "Age sane, inquam. Duo Reges: constructio interrete. Quare ad ea primum, si videtur;",

                            "Quid, de quo nulla dissensio est? Tubulo putas dicere? Quis est tam dissimile homini. Quis negat?",

                            "Quo modo autem philosophus loquitur? Quantum Aristoxeni ingenium consumptum videmus in musicis? Immo videri fortasse. Erat enim Polemonis. Immo alio genere;",

                            "Sed nunc, quod agimus; Hunc vos beatum;",

                            "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",

                            "Occultum id dicis, vicimus.",

                            "Qualem igitur hominem natura inchoavit?",

                            "Si longus, levis dictata sunt. Sed ille, ut dixi, vitiose. At certe gravius. Proclivi currit oratio.",

                            "An eiusdem modi? Quid enim possumus hoc agere divinius? Si longus, levis. Ita prorsus, inquam;"
                            };

            for (int i = 0; i < 100; i++)
            {
                string messageText = text[r.Next(0, 9)];
                var randomContact = VmHelper.Locator.ViewModelContactList.Contacts[r.Next(0, VmHelper.Locator.ViewModelContactList.Contacts.Count - 1)];
                chat.DisplayMessage(new DisplayMessage(randomContact, messageText, DisplayMessageOptions.ChatMessageOption, DateTime.Now, i == 99));
            };
        }

        private async void SelectTabCommandAction(ViewModelTab tab)
        {
            await DispatcherHelper.RunAsync(async () =>
                {
                    this.IsTabListOpen = false;
                    await Task.Delay(1);
                    await Task.Run(async () =>
                         {
                             await DispatcherHelper.RunAsync(() => this.CurrentActiveViewModel = tab);
                         });
                });
            //});
        }

        private void ChatViewModels_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add
                || e.Action == NotifyCollectionChangedAction.Remove
                || e.Action == NotifyCollectionChangedAction.Reset)
            {
                CreateTabButtonImage();
            }
            ShowTabListCommand.RaiseCanExecuteChanged();
        }
        public void CreateTabButtonImage()
        {

            Messenger.Default.Send(new NotificationMessageAction<Uri>(this, this.ChatViewModels.Count, "CreateTabButtonImage", result =>
            {

                this.TabButtonImageUri = result;

            }));

        }


        private void ShowTabListCommandAction()
        {
            this.IsTabListOpen = !this.IsTabListOpen;
            this.IsLoginControlVisible = false;
            if (this.CurrentActiveViewModel != null)
            {
                ShowEmoticonPopup = false;
            }

        }


        private void ShowLoginControlCommandAction(object obj)
        {
            bool? show = null;
            if (obj != null)
            {
                bool b;
                if (Boolean.TryParse(obj.ToString(), out b))
                    show = b;
            }
            //  ShowConnectPopup = !ShowConnectPopup;
            IsLoginControlVisible = show ?? !IsLoginControlVisible;
        }

        private void LoginCommandAction()
        {
            if (_currentClient.IsLoggedIn)
                DisconnectCommand.Execute(false);
            else
                _currentClient.StartConnectTask(false);
#if WINDOWS_PHONE_APP
            IsLoginControlVisible = false;
#endif
        }

        //private ObservableCollection<IEmoticon> CreateDefaultEmoticonList()
        //{
        //    ObservableCollection<IEmoticon> list = new ObservableCollection<IEmoticon>();
        //    foreach (KeyValuePair<string[], string> kvp in StaticSettings.DefaultEmoticons)
        //    {
        //        list.Add(new JiveDefaultEmoticonModel() { EmoticonShortcut = kvp.Key, EmoticonPath = "Assets/DefaultEmoticons/" + kvp.Value });
        //    }
        //    return list;
        //}



        private void OpenGroup(ViewModelChat vm)
        {
            ViewModelChat existingchat = ChatViewModels.FirstOrDefault(x => x.ID == vm.ID) as ViewModelChat;
            if (existingchat == null)
            {
                ChatViewModels.Add(vm);
                CurrentActiveViewModel = vm;
            }
            else
            {
                CurrentActiveViewModel = existingchat;
            }
            SelectedPivotItemIndex = 0;
        }

        private void PinTabCommandAction(ViewModelTab tabToPin)
        {
            if (tabToPin == null)
                return;
            tabToPin.IsPinned = !tabToPin.IsPinned;
            RaisePropertyChanged("CurrentActiveViewModel");
        }

        /// <summary>
        /// Close all tabs, with optional tab to keep open
        /// </summary>
        /// <param name="tabToKeep"></param>
        private void CloseAllTabsCommandAction(ViewModelTab tabToKeep)
        {
            var tabs = new List<ViewModelTab>(this.ChatViewModels);
            foreach (ViewModelTab tab in tabs)
            {
                if (tabToKeep != null && tabToKeep.Equals(tab))
                    continue;
                this.CloseTabCommand.Execute(tab);
            }
        }



        private void OpenNotificationsWindowCommandAction()
        {
            //  IsMainMenuVisible = false;
            //  Messenger.Default.Send(new NotificationMessage(this, "OpenNotifications"));
            _navigationService.NavigateTo("NotificationsPage");
        }


        private async void CloseTabCommandAction(ViewModelTab vm)
        {
            await Task.Delay(1);
            await DispatcherHelper.UIDispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                 {
                     if (vm == null)
                         vm = this.CurrentActiveViewModel;

                     this.ChatViewModels.Remove(vm);
                     if (this.CurrentActiveViewModel == vm)
                         this.CurrentActiveViewModel = this.ChatViewModels.FirstOrDefault();

                     if (vm is ViewModelChat)
                     {
                         _currentClient.ClosedConversations[vm.ID] = (ViewModelChat)vm;
                     }
                     vm.IsCurrentActiveTab = false;
                     if (this.ChatViewModels.Count == 0)
                         this.IsTabListOpen = false;
                 });
        }

        private void EditFontCommandAction()
        {
            //   IsMainMenuVisible = false;
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "ChangeFont"));
        }


        private void GetEmoticonsCommandAction()
        {
            //   IsMainMenuVisible = false;
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "AddUserEmoticons"));
        }

        private void OpenOptionsCommandAction()
        {
            //  IsMainMenuVisible = false;
            //  Messenger.Default.Send(new NotificationMessage(this, "OpenOptions"));

            _navigationService.NavigateTo("SettingsPage");

        }

        private async void DisconnectCommandAction(bool isExit)
        {
            //  IsMainMenuVisible = false;
            _currentClient.StopReconnectRetrying = true;
            _currentClient.IsUserConnecting = !isExit;
            _currentClient.UserSettings.OpenChats = this.ChatViewModels
                .Where(vm => vm.GetType() == typeof(ViewModelGroupChat))
                .Select(vm => new OpenChat(vm.ID, vm.IsPinned, ChatType.GroupChat))
                .Union<OpenChat>(this.ChatViewModels.Where(vm => vm.GetType() == typeof(ViewModelPrivateMessage))
                .Select(vm => new OpenChat(vm.ID, vm.IsPinned, ChatType.PrivateMessage)))
                .ToList();
            //_currentClient.Connection.SendPrepareLogout();
            //_currentClient.Connection.SendMessage(new ChatMessage(_currentClient.CurrentUserInfo, MessageType.PrepareLogout));
            await _currentClient.Connection.SendMessage(new ChatMessage(_currentClient.CurrentUserInfo.ID, _currentClient.CurrentUserInfo.UserName, MessageType.UpdateNotifications)).ConfigureAwait(false);
            await _currentClient.Connection.SendCommand(_currentClient.UserSettings, ClientCommands.WpSettings).ConfigureAwait(false);
             _currentClient.Connection.Disconnect();
        }

        public override void Cleanup()
        {
            //this.CurrentActiveViewModel = null;
            //this.ChatViewModels.Clear();

            // base.Cleanup();
        }
        public void RestoreTabs()
        {
            //   var locator = VmHelper.Locator;

            foreach (OpenChat openChat in _currentClient.UserSettings.OpenChats)
            {
                if (!this.ChatViewModels.Any(x => x.ID == openChat.ID))
                {
                    ViewModelChat vm = null;
                    if (!_currentClient.ClosedConversations.TryRemove(openChat.ID, out vm))
                    {
                        if (openChat.Type == ChatType.GroupChat)
                        {
                            Messenger.Default.Send(new NotificationMessageAction<IContact>(this, ViewModelContactList.MessengerCommands.GetCurrentUserContact.ToString(), contact =>
                                {
                                    IChatGroup group = contact.ChatGroups.FirstOrDefault(x => x.ID == openChat.ID);
                                    if (group != null)
                                    {
                                        vm = new ViewModelGroupChat(_currentClient, group) { IsPinned = openChat.IsPinned };
                                    }
                                }));
                        }
                        else if (openChat.Type == ChatType.PrivateMessage)
                        {
                            Messenger.Default.Send(new NotificationMessageAction<IEnumerable<IContact>>(this, ViewModelContactList.MessengerCommands.GetContacts.ToString(), contacts =>
                                {
                                    var contact = contacts.FirstOrDefault(x => x.UserName == openChat.ID);
                                    if (contact != null)
                                    {
                                        vm = new ViewModelPrivateMessage(_currentClient, contact) { IsPinned = openChat.IsPinned };
                                    }
                                }));
                        }
                    }
                    if (vm != null)
                        this.ChatViewModels.Add(vm);
                }
            }
            CurrentActiveViewModel = this.ChatViewModels.FirstOrDefault();

            this.IsLoginControlVisible = false;
            IsChatControlVisible = true;
        }
        internal void RefreshIcons()
        {
            if (StaticSettings.CurrentTheme == PhoneTheme.Dark || StaticSettings.CurrentTheme == PhoneTheme.HighContrastDark)
                this.JiveIcon = "ms-appx:///Assets/Images/jive_icon_white.png";
            else
                this.JiveIcon = "ms-appx:///Assets/Images/jive_icon.png";
        }
        public void RunOnNetworkConnect()
        {
            if (!String.IsNullOrEmpty(_currentClient.CurrentUserInfo.NickName))
                this.WindowTitle = "Jive Messenger" + " - " + _currentClient.CurrentUserInfo.NickName + " <" + _currentClient.CurrentUserInfo.UserName + ">";
            else
                this.WindowTitle = "Jive Messenger" + " - " + _currentClient.CurrentUserInfo.UserName;

            //  var locator = VmHelper.Locator;
            // locator.ViewModelNotifications.Notifications.Add(new FriendInviteNotification() { IsRead = false, NotificationText = "join plx", SenderUsername = locator.CurrentClient.CurrentUserInfo.UserName });
            // locator.ViewModelNotifications.Notifications.Add(new GroupInviteNotification() { IsRead = false, Group = locator.CurrentClient.CurrentUserInfo.ChatGroups.FirstOrDefault(), NotificationText = "join gruppe", SenderUsername = locator.CurrentClient.CurrentUserInfo.UserName });

            this.ConnectButtonDisplayText = "Log out";
            this.IsLoginControlVisible = false;
            IsChatControlVisible = true;
            RaisePropertyChanged("EmptyClientListText");

            //foreach (ViewModelChat vm in ChatViewModels.Where(x => x is ViewModelChat))
            //{
            //    foreach (MessageModel msg in vm.Messages)
            //        msg.Refresh();
            //}
            if (_currentClient.CurrentUserInfo.ChatGroups.Count > 0)
            {
                //     var locator = VmHelper.Locator;

                foreach (OpenChat openChat in _currentClient.UserSettings.OpenChats)
                {
                    if (!this.ChatViewModels.Any(x => x.ID == openChat.ID))
                    {
                        ViewModelChat vm = null;
                        if (!_currentClient.ClosedConversations.TryRemove(openChat.ID, out vm))
                        {
                            if (openChat.Type == ChatType.GroupChat)
                            {
                                Messenger.Default.Send(new NotificationMessageAction<IContact>(this, ViewModelContactList.MessengerCommands.GetCurrentUserContact.ToString(), contact =>
                                    {
                                        IChatGroup group = contact.ChatGroups.FirstOrDefault(x => x.ID == openChat.ID);
                                        if (group != null)
                                            vm = new ViewModelGroupChat(_currentClient, group) { IsPinned = openChat.IsPinned };
                                    }));
                            }
                            else if (openChat.Type == ChatType.PrivateMessage)
                            {
                                Messenger.Default.Send(new NotificationMessageAction<IEnumerable<IContact>>(this, ViewModelContactList.MessengerCommands.GetContacts.ToString(), contacts =>
                                    {
                                        var contact = contacts.FirstOrDefault(x => x.UserName == openChat.ID);
                                        if (contact != null)
                                            vm = new ViewModelPrivateMessage(_currentClient, contact) { IsPinned = openChat.IsPinned };
                                    }));
                            }
                        }
                        if (vm != null)
                            this.ChatViewModels.Add(vm);
                    }
                }
                CurrentActiveViewModel = this.ChatViewModels.FirstOrDefault();

            }
            ShowTabListCommand.RaiseCanExecuteChanged();
            OpenEmoticonsCommand.RaiseCanExecuteChanged();
        }

        public void RunOnNetworkDisconnect()
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    this.WindowTitle = "Jive Messenger";
                    this.ConnectButtonDisplayText = "Log in";
                    this.ShowEmoticonPopup = false;
                    RaisePropertyChanged("EmptyClientListText");
                    OpenEmoticonsCommand.RaiseCanExecuteChanged();
                    ShowTabListCommand.RaiseCanExecuteChanged();
                });
            // this.IsLoginControlVisible = true;
        }
    }
}